package com.assetmanage.controller;

import com.assetmanage.model.User;
import com.assetmanage.service.UserService;
import com.assetmanage.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.BufferedReader;

@WebServlet("/api/users")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    // 用户登录
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String requestBody = sb.toString();
            System.out.println("收到的登录请求数据: " + requestBody);  // 打印接收到的数据
            
            if (requestBody == null || requestBody.isEmpty()) {
                writeError(resp, "请求体为空");
                return;
            }

            // 解析JSON数据
            JsonNode jsonNode = MAPPER.readTree(requestBody);
            if (jsonNode == null) {
                writeError(resp, "JSON解析失败");
                return;
            }

            JsonNode usernameNode = jsonNode.get("username");
            JsonNode passwordNode = jsonNode.get("password");

            if (usernameNode == null || passwordNode == null) {
                writeError(resp, "用户名或密码字段缺失");
                return;
            }

            String username = usernameNode.asText();
            String password = passwordNode.asText();

            if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
                writeError(resp, "用户名或密码不能为空");
                return;
            }

            User user = userService.login(username, password);
            if (user != null) {
                HttpSession session = req.getSession();
                session.setAttribute("user", user);
                writeSuccess(resp, user);
            } else {
                writeError(resp, "用户名或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "登录失败：" + e.getMessage());
        }
    }

    // 获取所有用户
    public void getAllUsers(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writeSuccess(resp, userService.getAllUsers());
    }

    // 根据部门获取用户
    public void getUsersByDepartment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String depId = req.getParameter("depId");
        if (depId == null) {
            writeError(resp, "部门ID不能为空");
            return;
        }
        writeSuccess(resp, userService.getUsersByDepartment(depId));
    }

    // 添加用户
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = MAPPER.readValue(req.getInputStream(), User.class);
        if (userService.addUser(user)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "添加用户失败");
        }
    }

    // 更新用户
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 使用传统的方式读取请求体
            StringBuilder requestBody = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }

            System.out.println("收到的请求体: " + requestBody.toString());
            User user = MAPPER.readValue(requestBody.toString(), User.class);
            System.out.println("解析后的用户对象: " + user);

            if (userService.updateUser(user)) {
                writeSuccess(resp, null);
            } else {
                writeError(resp, "更新用户失败");
            }
        } catch (Exception e) {
            System.out.println("更新用户时发生错误: " + e.getMessage());
            e.printStackTrace();
            writeError(resp, "服务器内部错误：" + e.getMessage());
        }
    }

    // 删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uIdStr = req.getParameter("uId");
        if (uIdStr == null) {
            writeError(resp, "用户ID不能为空");
            return;
        }

        try {
            int uId = Integer.parseInt(uIdStr);
            if (userService.deleteUser(uId)) {
                writeSuccess(resp, null);
            } else {
                writeError(resp, "删除用户失败");
            }
        } catch (NumberFormatException e) {
            writeError(resp, "用户ID必须是数字");
        }
    }

    // 获取用户信息
    public void getUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uIdStr = req.getParameter("uId");
        if (uIdStr == null) {
            writeError(resp, "用户ID不能为空");
            return;
        }

        try {
            int uId = Integer.parseInt(uIdStr);
            User user = userService.getUserById(uId);
            if (user != null) {
                writeSuccess(resp, user);
            } else {
                writeError(resp, "用户不存在");
            }
        } catch (NumberFormatException e) {
            writeError(resp, "用户ID必须是数字");
        }
    }

    // 检查是否是管理员
    public void isAdmin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uIdStr = req.getParameter("uId");
        if (uIdStr == null) {
            writeError(resp, "用户ID不能为空");
            return;
        }

        try {
            int uId = Integer.parseInt(uIdStr);
            writeSuccess(resp, userService.isAdmin(uId));
        } catch (NumberFormatException e) {
            writeError(resp, "用户ID必须是数字");
        }
    }
} 